﻿using System;
using DataService.Enums;
using DataService.Group;
using DataService.Structs;

namespace DataService.Tag;

public sealed class StringTag : TagBase
{
    string _str;
    public string String
    {
        get
        {
            return _str;
        }
        set
        {
            _str = value;
        }
    }

    public StringTag(short id, DeviceAddress addr, IGroup group)
        : base(id, addr, group)
    {
    }


    #region IDevice Members
    public override bool Refresh(DataSource source = DataSource.Device)
    {
        var _newvalue = _group.ReadString(_plcAddress, source);
        if (_newvalue.Value != _str)
        {
            DateTime time = _newvalue.TimeStamp.ToDateTime();
            if (ValueChanging != null)
            {
                ValueChanging(this, new ValueChangingEventArgs<Storage>(_newvalue.Quality, _value, _value, _timestamp, time));
            }
            _timestamp = time;
            _quality = _newvalue.Quality;
            if (_quality == QUALITIES.QUALITY_GOOD)
            {
                _str = _newvalue.Value;
                if (ValueChanged != null)
                {
                    ValueChanged(this, new ValueChangedEventArgs(_value));
                }
            }
            return true;
        }
        return false;
    }

    public override Storage Read(DataSource source = DataSource.Cache)
    {
        var value = _group.ReadString(_plcAddress, source);
        if (value.Quality == QUALITIES.QUALITY_GOOD)
            _str = value.Value;
        return Storage.Empty;
    }

    public override int Write(object value)
    {
        if (value == null) return -1;
        var str = value is string ? (string)value : value.ToString();
        //_timeStamp = DateTime.Now;
        return _group.WriteString(_plcAddress, str);
    }

    protected override int InnerWrite(Storage value)
    {
        return _group.WriteString(_plcAddress, _str);
    }

    #endregion

    public override string ToString()
    {
        return _str ?? string.Empty;
    }
}
